package com.tarena.lbs.business.service.impl;

import com.tarena.lbs.attach.api.AttachApi;
import com.tarena.lbs.attach.pojo.param.PicUpdateParam;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.business.constant.PictureTypes;
import com.tarena.lbs.business.dao.repository.BusinessRepository;
import com.tarena.lbs.business.dao.repository.StoreRepository;
import com.tarena.lbs.business.pojo.param.StoreParam;
import com.tarena.lbs.business.pojo.param.UserLocationParam;
import com.tarena.lbs.business.pojo.po.BusinessPO;
import com.tarena.lbs.business.pojo.query.AreaStoreQuery;
import com.tarena.lbs.business.pojo.query.StoreQuery;
import com.tarena.lbs.business.pojo.vo.StoreVO;
import com.tarena.lbs.business.service.StoreService;
import com.tarena.lbs.common.enums.Roles;
import com.tarena.lbs.common.principle.UserPrinciple;
import com.tarena.lbs.common.utils.AuthenticationContextUtils;

import com.tarena.lbs.user.dao.repository.AdminRepository;
import com.tarena.lbs.user.pojo.po.AdminPO;

import io.jsonwebtoken.lang.Assert;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class StoreServiceImpl implements StoreService {
    @Autowired
    private StoreRepository storeRepository;
    @Autowired
    private BusinessRepository businessRepository;
    @DubboReference
    private AttachApi attachApi;
    @DubboReference
    private AdminRepository adminRepository;

    @Override
    public void save(StoreParam param) throws BusinessException {
        checkRole(Roles.SHOP);
        log.info("业务层保存店铺信息:{}", param);
        BusinessPO po=selectByBusinessId(param.getBusinessId());
        if (po==null){
            throw new BusinessException("-1", "商家不存在");
        }
        Integer id =storeRepository.save(param);
        log.info("保存店铺信息成功，返回的ID为：{}", id);
        bingPicture(id,param);

    }

    private void bingPicture(Integer id, StoreParam param) {
        log.debug("绑定图片");
        //绑定图片的业务 是根据入参中的图片ids logo 照片 绑定的当前店铺
        //1.准备封装一个调用绑定图片的参数
        List<PicUpdateParam> picParams=new ArrayList<>();
        //2.封装一个logo参数
        PicUpdateParam logoParam=new PicUpdateParam();
        logoParam.setBusinessId(id);
        logoParam.setBusinessType(PictureTypes.BIZ_STORE_LOGO);
        logoParam.setId(Integer.valueOf(param.getStoreLogo()));
        picParams.add(logoParam);
        //3.封装一组 店铺门店图片
        List<String> storeImagesIds = param.getStoreImagesIds();
        List<PicUpdateParam> storeImagesParams=
                storeImagesIds.stream().map(storeImageId->{
                    PicUpdateParam storeImageParam=new PicUpdateParam();
                    storeImageParam.setBusinessType(PictureTypes.BIZ_STORE_LICENSE);
                    storeImageParam.setBusinessId(id);
                    storeImageParam.setId(Integer.valueOf(storeImageId));
                    return storeImageParam;
                }).collect(Collectors.toList());
        //将门店图片 参数 全部 加入到 远程调用的入参里
        picParams.addAll(storeImagesParams);
        //发起远程dubbo调用
        boolean result = attachApi.batchUpdateBusiness(picParams);

    }

    private BusinessPO selectByBusinessId(Integer businessId) {
        BusinessPO po =businessRepository.selectById(businessId);
        return po;
    }

    private void checkRole(Roles roles) {
        log.debug("检查用户身份是否为商户");
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
        log.info("当前用户信息: {}", userPrinciple);
        Assert.isTrue(userPrinciple != null, new BusinessException("-1", "用户未登录或认证已过期").getMessage());
        Assert.isTrue(userPrinciple.getRole() == roles, new BusinessException("-1", "用户权限不足").getMessage());
    }

    @Override
    public List<StoreVO> selectList(StoreQuery query) throws BusinessException {
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
        Roles role=userPrinciple.getRole();
        if (role==Roles.SHOP){
            AdminPO ugp= adminRepository.getAdminById(userPrinciple.getId());
            if (ugp.getBusinessId()==null){
                throw new BusinessException("-1","用户未绑定商家");
            }else{
                query.setBusinessId(ugp.getBusinessId());
            }
            query.setBusinessId(ugp.getBusinessId());
        }
        List<StoreVO> list = storeRepository.select(query);
        log.info("查询店铺列表:{}", list);
        return list;
    }

    @Override
    public List<StoreVO> selectByCityId(AreaStoreQuery query) throws BusinessException {
        List<StoreVO> list = new ArrayList<>();
        for (int i=0;i<query.getCityIdList().size();i++){
            Long cityId = query.getCityIdList().get(i);
            List<StoreVO> listVO = storeRepository.selectByCityId(cityId);
            for (int j=0;j<listVO.size();j++) {
                list.add(listVO.get(j));
            }
        }
        if (list.size()==0){
            throw new BusinessException("-1","没有找到该城市下的店铺");
        }
        return list;
    }

    @Override
    public boolean saveUserLocation(UserLocationParam param) {
        boolean result=storeRepository.saveUserLocation(param);
        return result;
    }
}
